package com.org.khtn.command.insert;

import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

import com.org.khtn.command.MyQuery;
import com.org.khtn.command.insert.ParseInsert;
import com.org.khtn.data.Data;
import com.org.khtn.data.DataTables;
import com.org.khtn.data.Table;

public class InsertQuery extends MyQuery{
	final String className = getClass().getSimpleName()+":";
	Map<String, String> tableDefine;

	public InsertQuery(String Query, String databaseName) {
		dt = new DataTables(new Data(databaseName, "sadsa", "mytest\\data\\"));
		query = Query;
		parse = new ParseInsert(Query);
		table = dt.getAllTableName();

	}

	public static void main(String[] args) {
		InsertQuery a = new InsertQuery(
				"insert into sach (masach,name) values ('12','son25')",
				"qlhs");
		System.out.println(a.executeNonQuery());
	}

	public boolean fieldsExist(String[] fields) {
		int length = fields.length;
		for (int i = 0; i < length; i++)

		{
			if (!tableDefine.containsKey(fields[i]))
				return false;
		}
		return true;
	}
	/**
	 * 
	 * @return 1 neu thanh cong, -10 neu xai syntax
	 */
	@Override
	public int executeNonQuery() {
		// TODO Auto-generated method stub
		final String methodName = getClass().getSimpleName() + "():";
		System.out.println(className +methodName+"vao 1");
		
		if (!parse.eval())
			return -10;
		else
			key = parse.parse();

		if (!tableExist(key[0]))
			return -11;
		tableDefine = dt.getTableDefines(key[0]);
		Table myTable = dt.getTable(key[0]);
		String[] fieldName = key[1].split(",");
		String[] fieldValue = key[2].split(",");
		if (fieldName.length < fieldValue.length)
			return -21;
		if (fieldName.length > fieldValue.length)
			return -22;
		if (!fieldsExist(fieldName))
			return -12;
		int length = fieldName.length;
		System.out.println(className +methodName+"vao 2");

		for (int i = 0; i < length; i++) {
			String type = tableDefine.get(fieldName[i]);
			int lengthValue = fieldValue[i].length();
			System.out.println(className +methodName+"fieldValue[i].charAt(0):"+fieldValue[i].charAt(0));

			if (fieldValue[i].charAt(0) == 39
					&& fieldValue[i].charAt(lengthValue - 1) == 39) {
				fieldValue[i] = fieldValue[i].substring(1, lengthValue - 1);
				System.out.println(className +methodName+"fieldValue[i]:"+fieldValue[i]);

				if (type.equalsIgnoreCase("int")) {
					try {
						Integer.parseInt(fieldValue[i]);
					} catch (NumberFormatException nf) {
						return -13;
					}
				}

			}

		}
		
		int result =dt.insertRecord(key[0], fieldName, fieldValue);

		return result;

	}

}